package com.how2java.tmall.service;


import com.how2java.tmall.dao.OrderItemDao;
import com.how2java.tmall.pojo.Order;
import com.how2java.tmall.pojo.OrderItem;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.User;
import com.how2java.tmall.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "orderItems")
public class OrderItemService {

    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private ProductImageService productImageService;

    public void fill(List<Order> orderList){
        for(Order order : orderList){
            fill(order);
        }
    }

    public void fill(Order order){
        OrderItemService orderItemService = SpringContextUtil.getBean(OrderItemService.class);
        List<OrderItem> orderItems = orderItemService.listByOrder(order);
        float total = 0;
        int totalNumber = 0;
        for(OrderItem oi : orderItems){
            total += oi.getNumber()*oi.getProduct().getPromotePrice();
            totalNumber+= oi.getNumber();
            productImageService.setFirstProductImage(oi.getProduct());
        }
        order.setTotal(total);
        order.setOrderItems(orderItems);
        order.setTotalNumber(totalNumber);
    }

    @Cacheable(key = "'orderItems-oid-'+#p0.id")
    public List<OrderItem> listByOrder(Order order){
        return orderItemDao.findByOrOrderOrderByIdDesc(order);
    }

    @Cacheable(key="'orderItems-pid-'+#p0.id")
    public int getSaleCount(Product product){
        List<OrderItem> ois = orderItemDao.findByProduct(product);
        int result = 0 ;
        for(OrderItem oi : ois){
            if(null != oi.getOrder() && null != oi.getOrder().getPayDate()){
                result += oi.getNumber();
            }
        }
        return  result;
    }

    /**
     * 根据用户获取购物车中产品的集合
     * @param user
     * @return
     */
    @Cacheable(key = "'orderItems-uid-'+#p0.id")
    public List<OrderItem> listByUser(User user){
        return orderItemDao.findByUserAndOrderIsNull(user);
    }

    @CacheEvict(allEntries = true)
    public void update(OrderItem oi) {
        orderItemDao.save(oi);
    }

    @CacheEvict(allEntries = true)
    public void add(OrderItem oi) {
        orderItemDao.save(oi);
    }

    @Cacheable(key="'orderItems-one-'+#p0")
    public OrderItem get(int id){
        return orderItemDao.findOne(id);
    }
    @CacheEvict(allEntries = true)
    public void delete(int id){
        orderItemDao.delete(id);
    }


}
